package com.xugongzhang.service;

import com.xugongzhang.dto.Message;
import com.xugongzhang.enums.MessageTypeEnum;
import com.xugongzhang.thread.ManageClientConnectServerThread;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @author X
 * @date 2022/11/27 23:56
 */
public class FileClientService {

    /**
     * @param src 源文件目录
     * @param dest 对方接收文件的目录
     * @param senderId 发送者
     * @param getterId 接收者
     */
    public void sendFileToOne(String src, String dest, String senderId, String getterId) {
        Message message = new Message();
        message.setMsgType(MessageTypeEnum.FILE_MSG.getMessageType());
        message.setSender(senderId);
        message.setGetter(getterId);
        message.setSrc(src);
        message.setDest(dest);
        
        // 先读文件
        FileInputStream fileInputStream = null;
        // 文件数组
        byte[] fileBytes = new byte[(int) new File(src).length()];

        try {
            fileInputStream = new FileInputStream(src);
            fileInputStream.read(fileBytes);
            message.setFileBytes(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("\n" + senderId + " 给 " + getterId 
                + " 发送文件：" + src + " 到对方的：" + dest);
        // 发送
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread.
                    getClientConnectServerThread(senderId).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
